import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:tx_plugin/qq_response.dart';
import 'package:tx_plugin/qq_sdk_params.dart';
import 'package:tx_plugin/tx_plugin.dart' as tx;
import 'package:tx_plugin/wechat_response.dart';
import 'package:tx_plugin/wx_sdk_params.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? _platformVersion = 'Unknown';

  late StreamSubscription<WeChatAuthResponse> _wxAuthStreamSubscription;
  late StreamSubscription<WeChatShareResponse> _wxShareStreamSubscription;
  late StreamSubscription<QQAuthResponse> _qqAuthStreamSubscription;
  late StreamSubscription<QQShareResponse> _qqShareStreamSubscription;
  late StreamSubscription<QQGetUserInfoResponse> _qqGetUserInfoStreamSubscription;

  static String kWXAppID = "wx8131fa0ca06ed1e6";
  static String kWxUniversalLinks = "https://www.xn--vuq861by66a.com";
  static String kQQAppID = "101815213";
  static String kQQUniversalLinks = "https://www.xn--vuq861by66a.com/qq_conn/101815213";
  static String kQQScope = "get_simple_userinfo";

  GlobalKey rootWidgetKey = GlobalKey();

  String? wxCode;

  @override
  void initState() {
    initPlatformState();
    super.initState();
    _initController();
  }

  @override
  void dispose() {
    _wxAuthStreamSubscription.cancel();
    _wxShareStreamSubscription.cancel();
    _qqAuthStreamSubscription.cancel();
    _qqShareStreamSubscription.cancel();
    _qqGetUserInfoStreamSubscription.cancel();
    super.dispose();
  }

  Future<void> initPlatformState() async {
    String? platformVersion;
    try {
      platformVersion = await tx.TxPlugin.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ListView(
            children: <Widget>[
              Text('Running on: $_platformVersion\n'),
              MaterialButton(
                onPressed: () {
                  print("注册微信的点击事件方法");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap(appId: kWXAppID, iOSUniversalLinks: kWxUniversalLinks);
                  tx.TxPlugin.registerToWx(wxSdkParamsMap).then((isSuccess) {
                    print('注册微信 - 最终结果:$isSuccess');
                  });
                },
                child: Text("注册微信"),
              ),
              MaterialButton(
                onPressed: () {
                  print("是否安装微信");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  tx.TxPlugin.isInstalledWx(wxSdkParamsMap).then((isInstalled) {
                    print('测试=isInstalledWx:$isInstalled');
                  });
                },
                child: Text("是否安装微信"),
              ),
              MaterialButton(
                onPressed: () {
                  print("调用微信进行授权的点击事件方法");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap(scope: "snsapi_userinfo");
                  tx.TxPlugin.authorizationByWx(wxSdkParamsMap);
                },
                child: Text("微信用户授权"),
              ),
              Text('微信code: ${wxCode ?? ''}'),
              Container(
                child: GestureDetector(
                  onTap: () {
                    Clipboard.setData(ClipboardData(text: wxCode));
                  },
                  behavior: HitTestBehavior.translucent,
                  child: Container(
                    padding: EdgeInsets.all(50),
                    color: Colors.green,
                    alignment: Alignment.center,
                    child: Text('复制微信 code'),
                  ),
                ),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享文本到微信好友");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  wxSdkParamsMap.text = "分享到微信的内容";
                  wxSdkParamsMap.targetScene = "0";
                  tx.TxPlugin.shareTextToWX(wxSdkParamsMap);
                },
                child: Text("分享文本到微信好友"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享文本到微信朋友圈");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  wxSdkParamsMap.text = "分享到微信的内容";
                  wxSdkParamsMap.targetScene = "1";
                  tx.TxPlugin.shareTextToWX(wxSdkParamsMap);
                },
                child: Text("分享文本到微信朋友圈"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享网络图片到微信好友");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  wxSdkParamsMap.imageUrl = "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg";
                  wxSdkParamsMap.thumbnail = "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg";
                  wxSdkParamsMap.targetScene = "0";
                  tx.TxPlugin.shareImageToWX(wxSdkParamsMap);
                },
                child: Text("分享网络图片到微信好友"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享网络图片到微信朋友圈");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  wxSdkParamsMap.imageUrl = "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg";
                  wxSdkParamsMap.thumbnail = "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg";
                  wxSdkParamsMap.targetScene = "1";
                  tx.TxPlugin.shareImageToWX(wxSdkParamsMap);
                },
                child: Text("分享网络图片到微信朋友圈"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享网页到微信好友");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  wxSdkParamsMap.webPageUrl = "https://www.baidu.com/";
                  wxSdkParamsMap.webPageTitle = "我是网页的标题我是网页的标题我是网页的标题我是网页的标题我是网页的标题我是网页的";
                  wxSdkParamsMap.webPageDescription = "我是网页的描述内容我是网页的描述内容我是网页的描述内容我是网页的描述";
                  wxSdkParamsMap.thumbnail = "https://img-dev.xn--vuq861by66a.com/s1/2019/11/21/6345517ead2f2776f680ec598e4df559.png";
                  wxSdkParamsMap.targetScene = "0";
                  tx.TxPlugin.shareWebPageToWX(wxSdkParamsMap);
                },
                child: Text("分享网页到微信好友"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享网页到微信朋友圈");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  wxSdkParamsMap.webPageUrl = "https://www.baidu.com/";
                  wxSdkParamsMap.webPageTitle = "我是网页的标题我是网页的标题我是网页的标题我是网页的标题我是网页的标题我是网页的";
                  wxSdkParamsMap.webPageDescription = "我是网页的描述内容我是网页的描述内容我是网页的描述内容我是网页的描述";
                  wxSdkParamsMap.thumbnail = "https://img-dev.xn--vuq861by66a.com/s1/2019/11/21/6345517ead2f2776f680ec598e4df559.png";
                  wxSdkParamsMap.targetScene = "1";
                  tx.TxPlugin.shareWebPageToWX(wxSdkParamsMap);
                },
                child: Text("分享网页到微信朋友圈"),
              ),
              MaterialButton(
                onPressed: () {
                  print("微信支付");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  wxSdkParamsMap.appId = kWXAppID;
                  wxSdkParamsMap.payPartnerId = "1900006771";
                  wxSdkParamsMap.payPrepayId = "wx22132239910080ca745d816c1889594632";
                  wxSdkParamsMap.payNonceStr = "cbaa91896db84b50f278c4251cc78b27";
                  wxSdkParamsMap.payTimeStamp = "1571721759";
                  wxSdkParamsMap.payPackageValue = "Sign=WXPay";
                  wxSdkParamsMap.paySign = "C9986BE3EB91E2ADCE2A776196AF2FB0";

                  tx.TxPlugin.payByWX(wxSdkParamsMap);
                },
                child: Text("微信支付"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享小程序");
                  WXSdkParamsMap wxSdkParamsMap = WXSdkParamsMap();
                  wxSdkParamsMap.miniProgramId = 'gh_65011bda52d1'; // 小程序ID
//                  wxSdkParamsMap.miniProgramId = 'gh_d239a61d1158'; // 小程序ID
                  wxSdkParamsMap.miniProgramPath = "/pages/index/index"; // 小程序页面路径
                  wxSdkParamsMap.miniProgramWebPageUrl = "https://www.baidu.com/"; // 兼容老版的url
                  wxSdkParamsMap.miniProgramWebPageTitle = "miniProgramWebPageTitle"; // 标题
                  wxSdkParamsMap.miniProgramWebPageDescription = "miniProgramWebPageDescription"; // 描述
                  wxSdkParamsMap.miniProgramHdImageData =
                      "https://img-dev.xinxigu.com.cn/s1/2020/2/21/73c87f0b9ab2dabd518f80e9801ec2b5.jpg";
                  tx.TxPlugin.shareMiniProgramToWX(wxSdkParamsMap);
                },
                child: Text("分享小程序"),
              ),
              MaterialButton(
                onPressed: () {
                  print("QQ-是否授权获取设备信息");
                  tx.TxPlugin.qqIsAuthGetDeviceInfo().then((success) {
                    print('测试=qqIsAuthGetDeviceInfo:$success');
                  });
                },
                child: Text("QQ-是否授权获取设备信息"),
              ),
              MaterialButton(
                onPressed: () {
                  print("QQ注册");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID, iOSUniversalLinks: kQQUniversalLinks);
                  tx.TxPlugin.registerToQQ(qqSdkParamsMap).then((success) {
                    print('测试=QQInstalled:$success');
                  });
                },
                child: Text("QQ注册"),
              ),
              MaterialButton(
                onPressed: () {
                  print("QQ用户授权");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID, scope: kQQScope);
                  tx.TxPlugin.authorizationByQQ(qqSdkParamsMap);
                },
                child: Text("QQ用户授权"),
              ),
              MaterialButton(
                onPressed: () {
                  print("是否安装QQ");
                  tx.TxPlugin.isInstalledByQQ().then((success) {
                    print('测试=QQInstalled:$success');
                  });
                },
                child: Text("是否安装QQ"),
              ),
//              MaterialButton(
//                onPressed: () {
//                  print("获取QQ用户信息");
//                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
//                  tx.TxPlugin.getUserInfoByQQ(qqSdkParamsMap);
//                },
//                child: Text("获取QQ用户信息"),
//              ),
              MaterialButton(
                onPressed: () {
                  print("退出QQ");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                  tx.TxPlugin.qqLogout(qqSdkParamsMap);
                },
                child: Text("退出QQ"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享新闻给QQ好友");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                  qqSdkParamsMap.targetScene = "Friend";
                  qqSdkParamsMap.title = "分享音乐给QQ好友Title";
                  qqSdkParamsMap.summary = "分享音乐给QQ好友Summary";
                  qqSdkParamsMap.imageUri = qqSdkParamsMap.imageUri = []
                    ..add("https://img-dev.xn--vuq861by66a.com/s1/2019/11/21/6345517ead2f2776f680ec598e4df559.png");
                  qqSdkParamsMap.targetUrl = "https://www.baidu.com/";
                  qqSdkParamsMap.networkImageUrl =
                      "https://img-dev.xinxigu.com.cn/s1/2020/10/26/e2d9dd9e22f834bc95192118f0bb4e8f_thumbnails.jpg";
                  qqSdkParamsMap.appName = "信息谷";
                  tx.TxPlugin.shareWebPageToQQ(qqSdkParamsMap);
                },
                child: Text("分享新闻给QQ好友"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享新闻给QQ空间");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                  qqSdkParamsMap.targetScene = "Qzone";
                  qqSdkParamsMap.title = "分享音乐给QQ空间Title";
                  qqSdkParamsMap.summary = "分享音乐给QQ空间Summary";
                  qqSdkParamsMap.imageUri = qqSdkParamsMap.imageUri = []
                    ..add("https://img-dev.xn--vuq861by66a.com/s1/2019/11/21/6345517ead2f2776f680ec598e4df559.png");
                  qqSdkParamsMap.networkImageUrl =
                      "https://img-dev.xinxigu.com.cn/s1/2020/10/26/e2d9dd9e22f834bc95192118f0bb4e8f_thumbnails.jpg";
                  qqSdkParamsMap.targetUrl = "https://www.baidu.com/";
                  qqSdkParamsMap.appName = "信息谷";
                  tx.TxPlugin.shareWebPageToQQ(qqSdkParamsMap);
                },
                child: Text("分享新闻给QQ空间"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享图文到QQ好友 - android");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                  qqSdkParamsMap.targetScene = "Friend";
                  qqSdkParamsMap.title = "分享图文给QQ好友Title";
                  qqSdkParamsMap.summary = "分享图文给QQ好友Summary";
                  qqSdkParamsMap.imageUri = []
                    ..add("/sdcard/DCIM/Camera/1142512304.jpeg")
                    ..add("/sdcard/DCIM/Camera/144517393228852888665");
                  qqSdkParamsMap.targetUrl = "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg";
                  qqSdkParamsMap.appName = "信息谷";
                  tx.TxPlugin.shareTextToQQ(qqSdkParamsMap);
                },
                child: Text("分享图文到QQ好友 - android"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享文本到QQ好友 - ios");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                  qqSdkParamsMap.targetScene = "Friend";
                  qqSdkParamsMap.title = "分享图文给QQ好友Title";
                  qqSdkParamsMap.summary = "分享图文给QQ好友Summary";
                  qqSdkParamsMap.imageUri = []
                    ..add("/sdcard/DCIM/Camera/1142512304.jpeg")
                    ..add("/sdcard/DCIM/Camera/144517393228852888665");
                  qqSdkParamsMap.targetUrl = "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg";
                  qqSdkParamsMap.appName = "信息谷";
                  tx.TxPlugin.shareTextToQQ(qqSdkParamsMap);
                },
                child: Text("分享文本到QQ好友 - iOS"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享图文到QQ空间 - android");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                  qqSdkParamsMap.targetScene = "Qzone";
                  qqSdkParamsMap.title = "分享图文给QQ好友Title";
                  qqSdkParamsMap.summary = "分享图文给QQ好友Summary";
                  qqSdkParamsMap.imageUri = qqSdkParamsMap.imageUri = []
                    ..add("/sdcard/DCIM/Camera/1142512304.jpeg")
                    ..add("/sdcard/DCIM/Camera/144517393228852888665");
                  qqSdkParamsMap.targetUrl = "http://a.hiphotos.baidu.com/image/pic/item/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg";
                  qqSdkParamsMap.appName = "信息谷";
                  tx.TxPlugin.shareTextToQQ(qqSdkParamsMap);
                },
                child: Text("分享图文到QQ空间 - android"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享文本到QQ空间 - ios");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                  qqSdkParamsMap.targetScene = "Qzone";
                  qqSdkParamsMap.title = "分享图文给QQ好友Title";
                  qqSdkParamsMap.summary = "分享图文给QQ好友Summary";
                  qqSdkParamsMap.imageUri = qqSdkParamsMap.imageUri = []
                    ..add("/sdcard/DCIM/Camera/1142512304.jpeg")
                    ..add("/sdcard/DCIM/Camera/144517393228852888665");
                  qqSdkParamsMap.targetUrl = "http://a.hiphotos.baidu.com/image/pic/item/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg";
                  qqSdkParamsMap.appName = "信息谷";
                  tx.TxPlugin.shareTextToQQ(qqSdkParamsMap);
                },
                child: Text("分享文本到QQ空间 - iOS"),
              ),
              RepaintBoundary(
                key: rootWidgetKey,
                child: MaterialButton(
                  onPressed: () {
                    print("分享url图片给QQ好友");
                    QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                    qqSdkParamsMap.targetScene = "Friend";
                    qqSdkParamsMap.networkImageUrl =
                        "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg";
                    qqSdkParamsMap.appName = "信息谷";
                    tx.TxPlugin.shareImageToQQ(qqSdkParamsMap);
                  },
                  child: Text("分享url图片给QQ好友 - ios"),
                ),
              ),

              MaterialButton(
                onPressed: () async {
                  print("分享图片给QQ好友");
                  RenderRepaintBoundary boundary = rootWidgetKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
                  var image = await boundary.toImage(pixelRatio: 3.0);

                  ByteData byteData = await (image.toByteData(format: ImageByteFormat.png) as FutureOr<ByteData>);
                  Uint8List pngBytes = byteData.buffer.asUint8List();

                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap();
                  qqSdkParamsMap.imageData = pngBytes;
                  qqSdkParamsMap.targetScene = "Friend";
                  tx.TxPlugin.shareImageToQQ(qqSdkParamsMap);
                },
                child: Text("分享图片给QQ好友"),
              ),
              MaterialButton(
                onPressed: () async {
                  print("分享图片给QQ空间");
                  RenderRepaintBoundary boundary = rootWidgetKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
                  var image = await boundary.toImage(pixelRatio: 3.0);

                  ByteData byteData = await (image.toByteData(format: ImageByteFormat.png) as FutureOr<ByteData>);
                  Uint8List pngBytes = byteData.buffer.asUint8List();

                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap();
                  qqSdkParamsMap.imageData = pngBytes;
                  qqSdkParamsMap.targetScene = "Qzone";
                  tx.TxPlugin.shareImageToQQ(qqSdkParamsMap);
                },
                child: Text("分享图片给QQ空间"),
              ),
              MaterialButton(
                onPressed: () {
                  print("分享音乐给QQ好友");
                  QQSDKParamMap qqSdkParamsMap = QQSDKParamMap(appId: kQQAppID);
                  qqSdkParamsMap.targetScene = "Friend";
                  qqSdkParamsMap.title = "分享音乐给QQ好友Title";
                  qqSdkParamsMap.summary = "分享音乐给QQ好友Summary";
                  qqSdkParamsMap.imageUri = qqSdkParamsMap.imageUri = []
                    ..add("/sdcard/DCIM/Camera/1142512304.jpeg")
                    ..add("/sdcard/DCIM/Camera/144517393228852888665");
                  qqSdkParamsMap.targetUrl = "www.baidu.com";
                  qqSdkParamsMap.musicUrl = "";
                  qqSdkParamsMap.appName = "信息谷";
                  tx.TxPlugin.shareMusicToQQ(qqSdkParamsMap);
                },
                child: Text("分享音乐给QQ好友"),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _initController() {
    // 微信登录监听
    _wxAuthStreamSubscription = tx.wxResponseFromAuth.listen((data) {
      print('微信登录监听*****');
      print('code: ${data.code}');
      print('type: ${data.type}');
      print('country: ${data.country}');
      print('lang: ${data.lang}');
      print('iOSDescription: ${data.iOSDescription}');
      print('errCode: ${data.errCode}');
      print('errStr: ${data.errStr}');

      setState(() {
        wxCode = data.code;
      });
    });
    // 微信分享监听
    _wxShareStreamSubscription = tx.wxResponseFromShare.listen((data) {
      print('微信分享监听：$data');
    });
    // QQ登录监听
    _qqAuthStreamSubscription = tx.qqResponseFromAuth.listen((data) {
      print('QQ登录监听');
      print('accessToken: ${data.accessToken}');
      print('openID: ${data.openID}');
    });
    // QQ分享监听
    _qqShareStreamSubscription = tx.qqResponseFromShare.listen((data) {
      print('QQ分享监听');
      print('errCode: ${data.errCode}');
    });
    // QQ获取用户信息监听
    _qqGetUserInfoStreamSubscription = tx.qqResponseFromGetUserInfo.listen((data) {
      print('QQ获取用户信息监听：$data');
      print('avatarUrl: ${data.avatarUrl}');
      print('province: ${data.province}');
      print('errCode: ${data.errCode}');
      print('city: ${data.city}');
      print('nickname: ${data.nickname}');
      print('gender: ${data.gender}');
      print('genderType: ${data.genderType}');
      print('year: ${data.year}');
    });
  }
}
